package com.example.lib.utils

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.core.content.FileProvider
import com.example.lib.LibApp
import java.io.File


@SuppressLint("HardwareIds")
object DeviceUtils {

    fun toSetting(context: Context) {
        val packageURI = Uri.fromParts("package", context.packageName, null)
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(intent)
    }

    fun isAppInstall(context: Context, appName: String): Boolean {
        var packageInfo: PackageInfo? = null
        try {
            packageInfo = context.packageManager.getPackageInfo(appName, 0)
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return packageInfo != null
    }

    fun installAPK(downloadFile: File) {
        try {
            val intent = Intent(Intent.ACTION_VIEW)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)//安装完成后打开新版本
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) // 给目标应用一个临时授权
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
                val uri = FileProvider.getUriForFile(LibApp.appContext,
                    LibApp.appContext.packageName + ".fileprovider",
                    downloadFile)
                intent.setDataAndType(uri, "application/vnd.android.package-archive")
            } else {
                intent.setDataAndType(Uri.fromFile(downloadFile), "application/vnd.android.package-archive")
            }
            LibApp.appContext.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

}